from django.contrib.auth import get_user_model
from django.db import close_old_connections
# from oauth2_provider.oauth2_validators import OAuth2Validator
from oauthlib.common import Request
from rest_framework_jwt.serializers import jwt_decode_handler
from rest_framework_jwt.serializers import jwt_get_username_from_payload
User = get_user_model()


class MyAuthMiddleware:
    """
    Custom middleware (insecure) that takes user IDs from the query string.
    """

    def __init__(self, inner):
        # Store the ASGI application we were passed
        self.inner = inner

    def __call__(self, scope):
        # Look up user from query string (you should also do things like
        # check it's a valid user ID, or if scope["user"] is already populated)
       # scope["user"] = User.objects.get(id=int(scope["query_string"]))
        # Return the inner application directly and let it run everything else
        scope["user"] = None
        token = bytes.decode(scope['query_string'])
        # request = Request
        if not token:
            return self.inner(scope)
        # flag = OAuth2Validator().validate_bearer_token(token=token, scopes=[], request=request)
        flag = True
        user = None
        try:
            payload = jwt_decode_handler(token)
            username = jwt_get_username_from_payload(payload)
            user = User.objects.get_by_natural_key(username)
        except Exception as e:
            flag = False
        close_old_connections()
        if flag:
            scope["user"] = user

        return self.inner(scope)
